package com.tuangou.tuangouorder.order.web;

import com.alipay.api.internal.util.AlipaySignature;
import com.tuangou.tuangouorder.order.config.AlipayTemplate;
import com.tuangou.tuangouorder.order.entity.OrderEntity;
import com.tuangou.tuangouorder.order.service.OrderService;
import com.tuangou.tuangouorder.order.vo.PayVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/*
    凤兮凤兮归故乡，遨游千里求其凰
    2021/6/18
*/
@RestController
@RequestMapping("/order/pay")
public class PayWebController {

    @Autowired
    private AlipayTemplate alipayTemplate;

    @Autowired
    private OrderService orderService;

    @Value("${alipay.alipay_public_key}")
    private String alipay_public_key;

    @Value("${alipay.charset}")
    private String charset;

    @Value("${alipay.sign_type}")
    private String sign_type;

    @RequestMapping(value = "/payOrder",produces = "text/html")
    public String payOrder(@RequestParam("orderId") String orderId) throws Exception {
        PayVo payVo = new PayVo();
        OrderEntity byId = orderService.getById(orderId);
        payVo.setOut_trade_no(byId.getOrderId());
        payVo.setTotal_amount(byId.getTotalMoney().toString());
        payVo.setSubject("支付吧！");
        String pay = alipayTemplate.pay(payVo);
        return pay;
    }

    @GetMapping("/return")
    public String ret(HttpServletRequest request) throws Exception {
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipay_public_key, charset, sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            System.out.println("trade_no:"+trade_no+"<br/>out_trade_no:"+out_trade_no+"<br/>total_amount:"+total_amount);

            //修改订单状态
            OrderEntity byId = orderService.getById(out_trade_no);
            byId.setStatus(2); //已付款
            orderService.updateById(byId);
        }else {
            System.out.println("验签失败");
        }
        return "a";
    }

}
